package com.mashibing.juc.c_008.interview;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName T01_WithoutVolatile
 * @Description 面试题
 * 实现一个容器，提供两个方法，add,size
 * 写两个线程，线程1添加10个元素到容器中，线程2实现监控元素的个数，当个数到达5的时候，线程2给出提示并结束
 *
 * 案例一 不能实现
 * @Author xiongwei.wu
 * @Date 2021/7/12 17:36
 **/
public class T01_WithoutVolatile {
    List list = new ArrayList<>();

    private void addObj(Object object) {
        list.add(object);
    }

    private int getSize() {
        return list.size();
    }

    public static void main(String[] args) {
        T01_WithoutVolatile t = new T01_WithoutVolatile();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                t.addObj(new Object());
                System.out.println("add " + i);
            }
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t1").start();

        new Thread(() -> {
            while (true) {
                if (t.getSize() == 5) {
                    break;
                }
            }
            System.out.println("t2 结束...");
        }, "t2").start();
    }
}
